home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2461 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can't figure this out
  5. Date: 21 Jan 1996 12:33:19 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4dttcv$a6p@umbc9.umbc.edu>
  8. References: <31000091.3778302@news.panix.com>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Dan'l <dm@panix.com> wrote:
  13. |> I am learning C and I have not had any problems understanding most
  14. |> concepts I have learned so far.  But to date I still can't figure out
  15. |> how the outcome of this program is 15.  Somehow one of the B's ends up
  16. |> a three and the other B a 5, or am I so off base that I can't see
  17. |> what's really happening.    Can someone please walk me through this
  18. |> one.                                             Thanks     Dan'l
  19. |> 
  20. |> #define A 3
  21. |> #define B A + A
  22. |> #define C B * B
  23. |> 
  24. |> main()
  25. |> {
  26. |>     printf("%d", C);
  27. |>     return 0;
  28. |> }
  29.  
  30. Well the preprocessor is very good at what it does which is simple textual
  31. substitution. What actually gets compiled is probably:
  32.  
  33. printf("%d", 3 + 3 * 3 + 3);
  34.  
  35. We know that * is always done before + according to C's rules of precedence.
  36. So This is now 3 + 9 + 3. Now order doesn't matter (left to right if you
  37. really are) since everything is +. This evaluates to 15 which is what you
  38. got. The solution is to fix the #defines by adding explicit ()'s.
  39.  
  40. #define A 3
  41. #define B ((A) + (A))
  42. #define C ((B) * (B))
  43.  
  44. Actually you don't need quite this many, but it's a good habit to get
  45. into. For instance, if A was an expression like (1+2) instead of simply 3
  46. then you would need this many.
  47.  
  48. Now the result should be 36.
  49. -- 
  50. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  51.  
  52. Jonas J. Schlein  (schlein@gl.umbc.edu)
  53.